package com.fsc.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.fsc.entity.domain.*;
import com.fsc.entity.vo.StudentCompletionVO;
import com.fsc.service.*;
import com.fsc.entity.vo.HomeworkInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
@Slf4j
@RestController
@RequestMapping("/homework")
public class HomeworkController {

    @Autowired
    private HomeworkInfoService homeworkInfoService;

    @Autowired
    private StuHomeworkInfoService stuHomeworkInfoService;

    @Autowired
    private StuPartTeachService stuPartTeachService;

    @Autowired
    private LoginInfoService loginInfoService;

    @Autowired
    private ClassInfoService classInfoService;

    /**
     * 查看登录的老师布置的作业
     * @return
     */
    @GetMapping("/assignments")
    public ResponseEntity<List<HomeworkInfoVO>> getHomeworkInfoVOs() {
        Integer loginId = Integer.parseInt((String) StpUtil.getLoginId());
        int role = loginInfoService.getRole(loginId);

        if(role==0 ||role == 1){
            return ResponseEntity.ok(homeworkInfoService.getHomeworkInfoVOsByTeacherId(loginId));
        }

        if(role == 2 || role ==3){
            return ResponseEntity.ok(stuHomeworkInfoService.getHomeworkByStudentId(loginId));
        }

        return ResponseEntity.badRequest().build();
    }
    /**
     * 获取该老师的全部班名，根据老师的id，获取老师的班级ids，然后获取所有的班级名，返回classInfo
     */
    @GetMapping("/classes/{teacherId}")
     public ResponseEntity<List<ClassInfo>> getClasses(@PathVariable Integer teacherId) {
        List<ClassInfo> classInfo = classInfoService.getClassByTeaId(teacherId);
        return ResponseEntity.ok(classInfo);
    }

    /**
     * 查看某次作业的完成情况es/
     * @param homeworkId
     * @return
     */
    @GetMapping("/completion/{homeworkId}")
    public ResponseEntity<List<StudentCompletionVO>> getHomeworkCompletion(@PathVariable Integer homeworkId) {
        Integer teacherId = Integer.parseInt((String) StpUtil.getLoginId());
        List<StudentCompletionVO> stuHomeworkInfos = stuHomeworkInfoService.getStuHomeworkInfosByHomeworkId(homeworkId,teacherId);

        return ResponseEntity.ok(stuHomeworkInfos);
    }
    /**
     * 老师布置作业，获取老师的登录id，根据id获取老师的班级，根据班级获取学生，将作业布置给学生
     */
    @PostMapping("/assignHomework")
    public ResponseEntity<Void> assignHomework(@RequestBody HomeworkInfo homeworkInfo) {
        Integer teacherId = Integer.parseInt((String) StpUtil.getLoginId());
        log.info("作业内容:"+homeworkInfo);
        homeworkInfo.setTeacherId(teacherId);
        homeworkInfo.setTime(LocalDateTime.now());
        homeworkInfoService.save(homeworkInfo);
        List<Integer> student = stuPartTeachService.getStudent(teacherId);
        Integer homeworkId = homeworkInfo.getId();
        stuHomeworkInfoService.addHomework(student,homeworkId);
        return ResponseEntity.ok().build();
    }
    /**
     * 老师对作业进行修改，根据作业的id去修改修改作业的标题、内容、科目、截止日期
     */
    @PostMapping("/updateHomework")
    public ResponseEntity<Void> updateHomework(@RequestBody HomeworkInfo homeworkInfo) {
        //log.info("作业内容:"+homeworkInfo);
        homeworkInfoService.updateById(homeworkInfo);
        return ResponseEntity.ok().build();
    }
    /**
     * 老师对作业进行删除，根据作业的id去删除作业
     */
    @DeleteMapping("/deleteHomework/{homeworkId}")
    public ResponseEntity<Void> deleteHomework(@PathVariable Integer homeworkId) {
        homeworkInfoService.removeById(homeworkId);
        stuHomeworkInfoService.deleteById(homeworkId);
        return ResponseEntity.ok().build();
    }
    /**
     * 老师根据学生的id和某次作业的id,查看学生作业的完成情况
     */
    @GetMapping("/completionStatus/{studentId}/{homeworkId}")
    public ResponseEntity<StudentCompletionVO> correctingHomework(@PathVariable Integer studentId, @PathVariable Integer homeworkId) {
        StudentCompletionVO completionVO = stuHomeworkInfoService.getHomeworkDetailsByStudentId(studentId, homeworkId);

        return ResponseEntity.ok(completionVO);
    }

    /**
     * 教师对作业进行批改
     */
    @PostMapping("/correctHomework")
    public ResponseEntity<String> correctHomework(
            @RequestBody StuHomeworkInfo stuHomeworkInfo) {
        // 调用服务层方法进行批改
        boolean isUpdated = stuHomeworkInfoService.updateHomeworkScore(stuHomeworkInfo.getId(), stuHomeworkInfo.getScore());
        if (isUpdated) {
            return ResponseEntity.ok("批改成功");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("批改失败");
        }
    }

    /**
     * 学生提交作业，前端传来学生的作业id,作业内容homeworkDetails，作业图片homeworkUrl，将数据修改到StuHomeworkInfo表中
     */
    @PostMapping("/submitHomework")
    public ResponseEntity<?> submitHomework(
            @RequestParam("homeworkId") Integer homeworkId,
            @RequestParam("text") String text,
            @RequestPart(value = "image", required = false) MultipartFile image) {
        Integer studentId = Integer.parseInt((String) StpUtil.getLoginId());
        try {
            // 检查 image 是否为 null，如果是，则只提交文本
            if (image == null) {
                stuHomeworkInfoService.submitHomeworkOnlyText(homeworkId, text, studentId);
            } else {
                stuHomeworkInfoService.submitHomework(homeworkId, text, image, studentId);

            }
            return ResponseEntity.ok().build();
        } catch (Exception e) { // 更广泛的异常捕获
            // 记录异常信息，例如使用 logger.error("Error submitting homework", e);
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 学生查看自己提交过的作业，根据点击进去的内容，将内容展示在页面上,根据homeworkId和studentId
     */
// 查询作业详情接口
    @GetMapping("/getHomeworkDetail")
    public ResponseEntity<?> getHomeworkDetail(Integer homeworkId, Integer studentId) {
        // 根据homeworkId和studentId查询作业详情
        StudentCompletionVO homeworkInfo = stuHomeworkInfoService.getHomeworkDetailsByStudentId(studentId,homeworkId);
        if (homeworkInfo != null) {
            return ResponseEntity.ok(homeworkInfo);
        } else {
            return ResponseEntity.notFound().build();
        }
    }


}